const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class GradeService extends Service {
  /**
   * * 成绩占比数据请求
   * @param {String} fromLink 详情请求地址
   * @return {Object} *
   */
  async proportion(fromLink) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = fromLink
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        const Ntable = []
        if (tableList.length > 0) {
          for (let i = 1; i < tableList[0].length - 1; i += 2) {
            const type = tableList[0][i]
            const score = tableList[1][i]
            const proportion = tableList[1][i + 1]
            if (!proportion || proportion === '0%') continue
            Ntable.push({ type, score, proportion })
          }
        }
        return Ntable
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return []
  }

  /**
   * * 课程成绩查询
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term = '') {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kscj/cjcx_list`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        kksj: term,
        kcxz: '',
        kcmc: '',
        xsfs: 'all',
        fxkc: '2',
        sfxsbcxq: '1',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const header = ['课程名称', '类型', '学分', '成绩', '绩点', '考核方式', '课程性质'] // 列名称
    if (res.status === 200) {
      try {
        const cb = (cell, rowIndex, colIndex) => {
          const value = cell.text().trim().replace(/\s/g, '') // 获取单元格内容
          if (rowIndex > 0 && colIndex === 5) { // 成绩一列单独处理，提取出详情占比链接
            const link = this.ctx.state.baseUrl + cell.children()[0].attribs.href.split('\'')[1]
            return [value, link]
          }
          return value
        }
        const tableList = tableToList(res.data.toString(), '#dataList', '', cb)
        if (tableList.length === 0) {
          this.ctx.state.message = '请求数据为空'
          return { table: {}, header: [] }
        }
        const columnNeed = [3, 6, 8, 5, 10, 12, 15] // 需要提取的列序号
        if (tableList.length === 0 || tableList[1][0] === '未查询到数据') return { table: {}, header }
        /* 获取成绩占比 */
        const P = []
        for (let i = 1; i < tableList.length; i++) {
          P.push(this.proportion(tableList[i][5][1]))
        }
        const resAll = await Promise.all(P)
        for (let i = 1; i < tableList.length; i++) {
          tableList[i][5][1] = resAll[i - 1]
        }
        /* end */
        const info = {}
        for (let i = 1; i < tableList.length; i++) {
          const term1 = tableList[i][1]
          if ((term1 in info) === false) { info[term1] = [] }
          const tem = []
          columnNeed.forEach((idx) => {
            if (idx === 4) { tem.push({ score: tableList[i][idx][0], from: tableList[i][idx][1] }) }
            else { tem.push(tableList[i][idx]) }
          })
          info[term1].push(tem)
        }
        console.log('info', info)
        return { table: info, header }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, header }
  }
}
